from typing import Optional
import uuid
import os
# - The code starts by importing the necessary libraries.

from fastapi import FastAPI, File
from fastapi.responses import FileResponse, PlainTextResponse
from fastapi_utils.tasks import repeat_every
from fastapi.middleware.cors import CORSMiddleware

import glob

import recognition
app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# - Next, it defines a function that will be called periodically to delete files from the /tmp directory.
# - The periodic function is defined as an event handler and has an interval of 36000 seconds (1 hour).
# - It also waits for the first file in the list before deleting it.

@app.on_event("startup")
@repeat_every(seconds=36000, wait_first=True)
def periodic():
  fileList = glob.glob('/tmp/*.jpg')
  for filePath in fileList:
    try:
      os.remove(filePath)
    except:
      print("Error while deleting file : ", filePath)

# - Next, a POST request is made to get all images from /tmp/<uuid> .
# - This request returns a PlainTextResponse object which contains all of the image's metadata including its filename and location on disk.
# - Then this information is passed into recognition so that it can process each image with its corresponding algorithm and return back results in JSON format.
@app.post("/get_result", response_class=PlainTextResponse)
def read_item( pic: bytes = File(...)):
  origin_name = "/tmp/" + str(uuid.uuid4()) + ".jpg"
  f = open(origin_name, "wb")
  f.write(pic)
  f.close()
  res_id = str(uuid.uuid4())
  recognition.process_image(origin_name, f"/tmp/{res_id}.jpg")
  return f"/result/{res_id}"

# - Finally, there are two GET requests: one for getting an individual image based on its ID and another for getting all images based on their IDs
@app.get("/result/{id}")
def get_id(id):
  return FileResponse(f"/tmp/{id}.jpg")
